package com.fulu.game.bi.mysql.config;

import com.fulu.game.bi.mysql.properties.MultipleDatabaseProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


@Slf4j
@Configuration
@EnableConfigurationProperties(
        {MultipleDatabaseProperties.class})
@MapperScan(basePackages = {"com.fulu.game.bi.mysql.playadmin"},
        sqlSessionFactoryRef = "playAdminDbSqlSessionFactory")
public class PlayAdminDbConfig extends AbstractDbConfig {

    @Autowired
    private MultipleDatabaseProperties multipleDatabaseProperties;

    @Bean(name = "playAdminDbDataSource")
    public DataSource dataSource() {
        DataSourceProperties dbProperties = multipleDatabaseProperties.getPlayAdminDb();

        return getDruidDataSource(dbProperties);
    }

    @Bean(name = "playAdminDbSqlSessionFactory")
    public SqlSessionFactory playAdminDbSqlSessionFactory(@Qualifier("playAdminDbDataSource") DataSource dataSource) throws Exception {
        String locationPattern = "classpath:META-INF/playAdmin/mybatis/*.xml";

        return getSqlSessionFactory(dataSource, locationPattern);
    }

    @Bean(name = "playAdminTransactionManager")
    public DataSourceTransactionManager playAdminTransactionManager(@Qualifier("playAdminDbDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "playAdminDbSqlSessionTemplate")
    public SqlSessionTemplate playAdminDbSqlSessionTemplate(@Qualifier("playAdminDbSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
